﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Security;
using System.Security.Cryptography.X509Certificates;
using System.Text;
using System.Web;
using System.Web.Configuration;

/// <summary>
/// 阿里短信
/// </summary>
public class SmsContext
{
    private const string host = "http://dxyzm.market.alicloudapi.com";
    private const string path = "/chuangxin/dxjk";
    private const string method = "POST";
    private string appcode = "";
    private string smstag = "五行商城";
    private int smstotal;

    private static SmsContext instance = null;
    public static SmsContext Instance
    {
        get
        {
            if (instance == null)
                instance = new SmsContext();
            return instance;
        }
    }

    public SmsContext()
    {
        appcode = WebConfigurationManager.AppSettings["sms_appcode"];
        smstag = WebConfigurationManager.AppSettings["sms_tag"];
    }

    /// <summary>
    /// 发送短信
    /// </summary>
    /// <param name="PhoneNumbers">必填:待发送手机号。支持以逗号分隔的形式进行批量调用，批量上限为1000个手机号码,批量调用相对于单条调用及时性稍有延迟,验证码类型的短信推荐使用单条调用的方式</param>
    /// <param name="ValidCode">可选:模板中的变量替换JSON串,如模板内容为"亲爱的${name},您的验证码为${code}"时,此处的值为</param>
    /// <param name="OutId">可选:outId为提供给业务方扩展字段,最终在短信回执消息中将此值带回给调用者</param>
    /// <param name="SignName">必填:短信签名-可在短信控制台中找到</param>
    /// <param name="TemplateCode">必填:短信模板-可在短信控制台中找到</param>
    public bool SendCode(string PhoneNumbers, string ValidCode, ref string msg)
    {
        var sms = $"【{smstag}】您本次验证码为{ValidCode}，30分钟内有效。切勿告知他人！";
        
        return Send(PhoneNumbers, sms, ref msg);
    }

    public bool Send(string PhoneNumbers, string sms, ref string msg)
    {
        bool result = false;
        try
        {
            String querys = string.Format("content={0}&mobile={1}", Functions.UrlEncode(sms), PhoneNumbers);
            String bodys = "";
            String url = host + path;
            HttpWebRequest httpRequest = null;
            HttpWebResponse httpResponse = null;

            if (0 < querys.Length)
            {
                url = url + "?" + querys;
            }

            if (host.Contains("https://"))
            {
                ServicePointManager.ServerCertificateValidationCallback = new RemoteCertificateValidationCallback(CheckValidationResult);
                httpRequest = (HttpWebRequest)WebRequest.CreateDefault(new Uri(url));
            }
            else
            {
                httpRequest = (HttpWebRequest)WebRequest.Create(url);
            }
            httpRequest.Method = method;
            httpRequest.Headers.Add("Authorization", "APPCODE " + appcode);
            if (0 < bodys.Length)
            {
                byte[] data = Encoding.UTF8.GetBytes(bodys);
                using (Stream stream = httpRequest.GetRequestStream())
                {
                    stream.Write(data, 0, data.Length);
                }
            }
            try
            {
                httpResponse = (HttpWebResponse)httpRequest.GetResponse();
            }
            catch (WebException ex)
            {
                httpResponse = (HttpWebResponse)ex.Response;
            }

            //Console.WriteLine(httpResponse.StatusCode);
            //Console.WriteLine(httpResponse.Method);
            //Console.WriteLine(httpResponse.Headers);
            Stream st = httpResponse.GetResponseStream();
            StreamReader reader = new StreamReader(st, Encoding.GetEncoding("utf-8"));
            msg = reader.ReadToEnd();
            result = true;
        }
        catch (Exception ex)
        {
            msg = ex.Message;
        }
        return result;
    }

    public static bool CheckValidationResult(object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors errors)
    {
        return true;
    }
}